"""
Created on 23-Jul-2009

@author: dexen
"""

import os
import time

import rpyc
from rpyc.utils import server

import dexen
from dexen.system import node
from dexen.system.base import service, MyManager
from dexen.system.node.master import comm
from dexen.system.node.master.slave_mgr import SlaveMgr

MyManager.register("MasterComm", comm.MasterComm)
   
#===============================================================================
# Helper
#===============================================================================
def start(_mastername, _nodename, _reg_addr):
    global conn, masterdir, manager, nodename, mastername, reg_addr
    
    reg_addr = _reg_addr
    nodename = _nodename
    mastername = _mastername
    manager = MyManager()
    manager.start()
     
    #logging.basicConfig(level=logging.DEBUG)

    masterdir = os.path.join(node.TEMP_DIR, _mastername)
    if not os.path.exists(masterdir):
        os.mkdir(masterdir)
    
    #logging.debug("My pid is %d", os.getpid())
    
    
    MasterService.ALIASES = [_mastername]
    svr = server.ThreadedServer(MasterService, 
                                protocol_config=service.default_config)
    
    conn = rpyc.connect(reg_addr[0], reg_addr[1])
    conn.root.register_master(mastername, (service.get_my_ip_addr(), svr.port))
    conn.close()
    
    svr.start()


    
#===============================================================================
# Service
#===============================================================================
class MasterService(dexen.Service):
    def on_connect(self):
        #logging.info("node_manager is connected")
        pass
    
    def on_disconnect(self):
        pass
        
    def schedule(self, slave_name):
        self.comm.put_slave(slave_name)

    def run_schema(self, spec):
        self.spec = rpyc.classic.obtain(spec)
        
        self.spec.masterdir = masterdir
        self.spec.mastername = mastername
        #self.schema_zip = schema_zip TODO: type buffer --> netref !
        print "master->run_schema(), the type, len", type(self.spec.schema_zip),\
                                                     len(self.spec.schema_zip)  
        self.comm = manager.MasterComm(mastername)
        #self.sp = mp.Process(target=scheduler.run, args=(self.spec, self.comm))
        self.sp = SlaveMgr(self.spec, self.comm, reg_addr)
        self.sp.name = "Scheduler"
        self.sp.start()
        print "Master is running"

    def get_info(self):
        return self.comm.get_info()
    
